package com.syh.appshare.services;

import java.util.List;

import com.syh.appshare.Constants;
import com.syh.appshare.Memory;
import com.syh.appshare.common.utils.LogUtil;
import com.syh.appshare.common.utils.Utils;
import com.syh.appshare.objects.InstalledApkInfo;

import android.app.ActivityManager;
import android.app.Service;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

/**
 * 检测当前程序的后台服务
 * @author shenyh
 *
 */
public class ShareServices extends Service {

	private final String tag="service";
	private final int MAX_TASK=1,NOTIFY=2;
	
	
	
	private ActivityManager activityManager;
	
	
	/**
	 * 正在运行的程序
	 */
	private List<RunningTaskInfo> runningTasks;
	/**
	 * 上一个应用程序包名
	 */
	private String lastPackageName=null;
	
	private Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case NOTIFY:{
					String packageName=msg.getData().getString(Constants.PACKAGE_NAME_TAG);
					String className=msg.getData().getString(Constants.CLASS_NAME_TAG);
					Utils.notifyShare(getApplicationContext(), packageName, className);
					break;
				}
			}
		}
	};
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		activityManager=(ActivityManager) getSystemService(ACTIVITY_SERVICE);
		
		new Thread(){
			@Override
			public void run() {
				try {
					while(true){
						LogUtil.debug(tag, "ShareServices is running. lastPackageName："+lastPackageName);
						//检测栈
						// 获取当前正在运行的任务
						runningTasks = activityManager.getRunningTasks(MAX_TASK);

						if(runningTasks!=null){
							String packageName=runningTasks.get(0).baseActivity.getPackageName();
							if(isWhiteList(packageName)){
								String className=runningTasks.get(0).baseActivity.getClassName();
								if(!packageName.equals(lastPackageName)){
									lastPackageName=packageName;
									Message msg=new Message();
									msg.what=NOTIFY;
									Bundle data=new Bundle();
									data.putString(Constants.PACKAGE_NAME_TAG, packageName);
									data.putString(Constants.CLASS_NAME_TAG, className);
									msg.setData(data);
									handler.sendMessage(msg);
								}
							}
						}
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
					LogUtil.error(tag, "check app InterruptedException e:"+e.toString());
					e.printStackTrace();
				} catch (Exception e) {
					LogUtil.error(tag, "check app Exception e:"+e.toString());
					e.printStackTrace();
				}
			}
			
		}.start();
		
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 包名是否在白名单中（白名单为非系统应用）
	 * @param packageName
	 * @return
	 */
	private boolean isWhiteList(String packageName){
		List<InstalledApkInfo> installedApkList=Memory.getInstance(ShareServices.this).getInstalledApkList();
		for(int i=0;i<installedApkList.size();i++){
			if(installedApkList.get(i).packageName.equals(packageName)){
				return true;
			}
		}
		return false;
	}
	
}
